#!/bin/sh
start() {

    rm -f /var/log/gateway.log
    
    if test -f /tmp/gateway.error; then
        mv -f /usr/bin/gateway.old /usr/bin/gateway
        chmod +x /usr/bin/gateway
        rm -f /tmp/gateway.update
        rm -f /tmp/gateway.error
    elif test -f /tmp/gateway.update; then
        mv -f /usr/bin/gateway /usr/bin/gateway.old
        mv -f /tmp/gateway.update /usr/bin/gateway
        chmod +x /usr/bin/gateway
    fi

    printf "Starting gateway: "
    start-stop-daemon -S -q -p /var/run/gateway.pid \
        --exec /usr/bin/gateway -- daemon
    if [ $? = 0 ] ; then 
        echo "OK"
    else 
        echo "FAIL. Rollbacking..."
        touch /tmp/gateway.error
        reboot
    fi
}
stop() {
    printf "Stopping gateway: "
    start-stop-daemon -K -q -p /var/run/gateway.pid
    [ $? = 0 ] && echo "OK" || echo "FAIL"
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart | reload)
    stop
    start
    ;;
*)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

exit $?
